package main;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import main.database.DatabaseMan;
import org.bson.Document;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Properties;

public class MailHelper {
    public static void sendMail(String sendUser, String sendAccount, String password, String toAccount, String title, String content) {
        String host = GlobalConfig.mailHost;

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        Properties props = System.getProperties();
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sendAccount, sendUser));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAccount));
            message.setSubject(title);
            message.setContent("" + content + "", "text/html;charset=utf-8");

            Transport transport = session.getTransport("smtp");
            transport.connect(host, sendAccount, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
        catch (Exception e) {
            Logman.error(e.getStackTrace().toString());
        }
    }

    public static boolean isEmailAlreadyExist(String email) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfUser);
        return collection.countDocuments(new BasicDBObject("email", email)) != 0;
    }
}
